package fr.laas.knxinterface.starting;

import java.io.IOException;

import fr.laas.knxinterface.commands.Commands;
import fr.laas.knxinterface.communication.RxSocket;
import fr.laas.knxinterface.communication.TxSocket;
import fr.laas.knxinterface.config.ServiceConfiguration;

/**
 * Template of the starting class. Starts all the components and the server with
 * the good configuration
 * 
 * @author Guillaume Garzone
 * 
 */
public class ServiceLaunching {

	private TxSocket txSocket;
	private RxSocket rxSocket;
	private Commands commands;
	private ServiceConfiguration config;

	/**
	 * Initialization of the service
	 */
	public ServiceLaunching() {
		this.txSocket = null;
		this.rxSocket = null;
		this.commands = new Commands();
		this.config = new ServiceConfiguration();
	}

	/**
	 * Starts the service
	 */
	public void startService() {
		this.config.loadProperties();
		// starting EIBD service
		this.startEibd(this.config.getIpRouteurKnx());
		// starting reception
		this.startRxSocket(this.config.getListeningPort());
		// starting transmission
		this.startTxSocket(this.config.getRemoteHost(),
				this.config.getSendingPort());
	}

	/**
	 * Allows to stop the services
	 */
	public void stopService() {

		if (this.txSocket != null) {
			this.txSocket.stopTransmission();
		}
		if (this.rxSocket != null) {
			this.rxSocket.stopServer();
		}
		if (this.commands != null) {
			this.commands.destroy();
		}

	}

	/**
	 * Starts the EIBD service
	 * 
	 * @param ipKnxRouter
	 *            needs the ip of the ip/KNX router
	 */
	public void startEibd(String ipKnxRouter) {
		this.commands.startEibd(ipKnxRouter);

	}

	/**
	 * Starts the transmission of the data from the bus
	 * 
	 * @param host
	 *            : gateway where the plugin OM2M/KNX is running (localhost by
	 *            default if the gateway runs this program too)
	 * @param port
	 */
	public void startTxSocket(String host, int port) {
		this.txSocket = new TxSocket(host, port);
		this.txSocket.start();
	}

	/**
	 * Starts the reception part to receive commands from OM2M
	 * 
	 * @param port
	 *            to listen to
	 */
	public void startRxSocket(int port) {
		rxSocket = new RxSocket(port);
		rxSocket.start();
	}

	/**
	 * Main program
	 * 
	 * @param args
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException,
			InterruptedException {

		// initialization
		final ServiceLaunching service = new ServiceLaunching();

		// starting all the services
		service.startService();

		// closes the connections when program is terminated or shut down
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				System.out.println("Shut down of services");
				service.stopService();
			}
		});
	}
}
